package com.example.bluetoothttss;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class BtUtils {
    private static final String TAG = "BtUtils";

    static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothSocket mSocket;
    private OutputStream mOutputStream;
    private boolean isRead;
    public static final Executor EXECUTOR = Executors.newCachedThreadPool();
    private OnReadListener mOnReadListener;
    private OnConnectListener mOnConnectListener;
    private boolean connected;

    private static BtUtils instance;

    private BtUtils() {
    }

    public static BtUtils getInstance() {
        if (instance == null) {
            instance = new BtUtils();
        }
        return instance;
    }


    /**
     * 关闭Socket连接
     */
    public void close() {
        try {
            if (mOnConnectListener != null) {
                mOnConnectListener.onConnect(false);
            }

            connected = false;
            isRead = false;
            if (mSocket != null) {
                mSocket.close();
            }

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void connect(final BluetoothDevice dev) {
        try {
            try {
                connected = false;
                isRead = false;
                if (mSocket != null) {
                    mSocket.close();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }

            final BluetoothSocket socket = dev.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
            // 开启子线程
            EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!socket.isConnected()) {
                            socket.connect();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        close();
                        return;
                    }

                    loopRead(socket); //循环读取
                }
            });
        } catch (Throwable e) {
            close();
        }
    }

    /**
     * 循环读取对方数据(若没有数据，则阻塞等待)
     */
    protected void loopRead(BluetoothSocket socket) {

        mSocket = socket;
        try {
            try {
                if (!mSocket.isConnected()) {
                    mSocket.connect();
                }
                connected = true;
                mOnConnectListener.onConnect(true);
                mOutputStream = mSocket.getOutputStream();
                InputStream inputStream = mSocket.getInputStream();
                byte[] buffer = new byte[1024];
                int length = 0;
                isRead = true;
                while (isRead) {
                    length = inputStream.read(buffer);
                    String read = new String(Arrays.copyOf(buffer, length));
                    Log.i(TAG, "read:" + read);
                    if (mOnReadListener != null) {
                        mOnReadListener.onRead(read);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                //连接失败
                Log.i(TAG, "连接失败\n" + e.getMessage());
                close();
                return;
            }
        } catch (Throwable e) {
            close();

            e.printStackTrace();
        }
    }


    public void setOnReadListener(OnReadListener listener) {
        this.mOnReadListener = listener;
    }

    public void setOnConnectListener(OnConnectListener listener) {
        this.mOnConnectListener = listener;
    }


    public boolean isConnected() {
        return connected;
    }
}
